package com.sjc.algorithm.leetcode;

/**
 * @author by SangJiacun
 * @Date 2020/5/14 22:42
 */
public class P02 {
    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyhead = new ListNode(0);
        ListNode p = l1, q = l2, current = dummyhead;
        int carry = 0;
        while(p != null || q != null){
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry+x+y;

            if(sum >= 10){
                current.next = new ListNode(sum%10);
                carry = 1;
            }else{
                current.next = new ListNode(sum);
                carry = 0;
            }

            current = current.next;
            if(null != p){p = p.next; }
            if(null != q){q = q.next;}
        }
        if(carry>0){
            current.next = new ListNode(carry);
        }
        return dummyhead.next;
    }

    public static void main(String[] args) {
        ListNode l11 = new ListNode(1);
        ListNode l12 = new ListNode(8);
        l11.next = l12;

        ListNode l21 = new ListNode(0);

        ListNode listNode = addTwoNumbers(l11, l21);
        while(null != listNode){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
